package com.czy.plugin.action;

import com.czy.plugin.util.ApiHelper;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.io.IOException;

/**
 * @author chenzy
 */
public class GenerateSwaggerApiAction extends AnAction {

    @Override
    public void update(@NotNull AnActionEvent event) {
        // 根据文件扩展名判断是否显示
        String extension = getFileExtension(event.getDataContext());
        event.getPresentation().setEnabledAndVisible("java".equals(extension));
    }

    @Override
    public void actionPerformed(AnActionEvent event) {
        Project currentProject = event.getProject();
        PsiFile psiFile = event.getData(LangDataKeys.PSI_FILE);
        if (currentProject != null && psiFile != null) {
            String className = psiFile.getName();
            String title = String.format("确认为%s生成@ApiModel注解?", className);
            JBPopupFactory instance = JBPopupFactory.getInstance();
            instance.createConfirmation(title, "确认", "我再想想", () -> {
                String path = psiFile.getVirtualFile().getPath();
                try {
                    psiFile.getVirtualFile().setBinaryContent(ApiHelper.setApiModel(path));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }, 0).showCenteredInCurrentWindow(currentProject);
        } else {
            Messages.showMessageDialog("未选中POJO文件!", "Fail", Messages.getWarningIcon());
        }
    }

    /**
     * 获取文件扩展名
     *
     * @param dataContext
     * @return
     */
    public static String getFileExtension(DataContext dataContext) {
        VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(dataContext);
        return file == null ? null : file.getExtension();
    }
}
